package com.lzq.config;

import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.stream.Stream;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

@Component
public class MyBeanPostProcessor implements BeanPostProcessor {

	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		Class<?> clazz = bean.getClass();
		if (clazz.getName().equals("com.lzq.service.MyBean")) {
			System.out.println("在postProcessBeforeInitialization方法中：");
			Field[] fields = clazz.getDeclaredFields();
			if (fields.length > 4) {
				System.out.println("Bean [name=" + beanName + ",Class=" + clazz.getName() + "] has " + fields.length
						+ " properties.");
				Stream.of(fields).forEach(f -> {
					System.out.println("property " + f.getName() + "type is " + f.getType());
				});
			}
			Type[] interfaces = clazz.getGenericInterfaces();
			if (interfaces.length > 1) {
				System.out.println("Bean [name=" + beanName + ",Class=" + clazz.getName() + "] implements "
						+ interfaces.length + " interface.");
				Stream.of(interfaces).forEach(f -> {
					System.out.println("Implemented interface: " + f.getTypeName());
				});
			}
		}

		return bean;
	}

	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		Class<?> clazz = bean.getClass();
		if (clazz.getName().equals("com.lzq.service.MyBean")) {
			System.out.println("postProcessAfterInitialization方法执行应该在init-method之后");
		}

		return bean;
	}

}
